use axum::{Json, http::HeaderMap};
use com::{ code, auth, sea_orm::connect, query, encrypt};
use sea_orm::{ entity::*, query::* };
use model::user::{ Entity, Column };

pub async fn login(Json(body):Json<JsonValue>) -> Result<Json<JsonValue>, Json<JsonValue>>{
    let username = query::str(&body,"username")?;
    let password = query::str(&body, "password")?;
    let conn = connect().await?;
    let result = Entity::find()
    .select_only()
    .filter( Column::Username.eq( &username ).or(Column::Phone.eq( &username )))
    .filter(Column::Password.eq( encrypt::md5::encode(password) ))
    .filter(Column::Disabled.ne(1))
    .columns([
        Column::Id, Column::Name, Column::Username, Column::Head, Column::Role
    ])
    .into_json()
    .one(&conn).await;
    
    match result {
        Ok(f) => auth::user_redis::create_token_save_redis(f),
        Err(e) => code::sys(e.to_string())
    }
}

pub async fn logout(header:HeaderMap) -> Result<Json<JsonValue>, Json<JsonValue>>{ auth::user_redis::logout(header) }